<template>
    <img :src="weatherIcon"/>
    <span class="wea">{{ weatherDescription }}</span>
    <span class="tem">{{ temperature }}°C</span>
    <span class="air">空气质量:{{ airQuality }}</span>
</template>

<script setup>
import { onMounted } from 'vue';
import { ref } from 'vue';

import qing from '@/assets/brand/qing.png';
import wu from '@/assets/brand/wu.png';
import yin from '@/assets/brand/yin.png';
import yu from '@/assets/brand/yu.png';
import xue from '@/assets/brand/xue.png';
import yun from '@/assets/brand/yun.png';


const weatherIcon = ref('--');
const temperature = ref('--');
const weatherDescription = ref('--');
const airQuality = ref('--');
const windSpeed = ref('--');


onMounted(() => {
    fetchWeather(); // 在组件挂载时启动定时器和获取天气信息
})

// 获取天气信息
const fetchWeather = async () => {
    const url = `https://gfeljm.tianqiapi.com/api?unescape=1&version=v63&appid=62422313&appsecret=7tPPQM63&cityid=101260103`;

    try {
        const response = await fetch(url);
        const data = await response.json();

        // 更新温度
        temperature.value = data.tem;

        // 更新天气描述
        weatherDescription.value = data.wea;

        // 更新天气图标
        let tianqi = qing; // 默认晴天
        switch (data.wea) {
            case '晴':
                tianqi = qing;
                break;
            case '阴':
                tianqi = yin;
                break;
            case '雨':
                tianqi = yu;
                break;
            case '雪':
                tianqi = xue;
                break;
            case '雾':
                tianqi = wu;
                break;
            case '多云':
                tianqi = yun;
                break;
            // 可以根据需要添加更多天气类型
            default:
                tianqi = qing; // 默认晴天
        }

        weatherIcon.value = tianqi;

        // 更新空气质量
        airQuality.value = data.air_level;

        // 更新风速
        windSpeed.value = data.win_speed;
    } catch (error) {
        console.error('获取天气信息失败:', error);
    }
};

</script>

<style scoped>
img {
    width: 2.56rem;
    margin-bottom: -0.2rem;
}

.wea {
    margin-right: 0.6rem;
}

.air {
    font-size: 1rem;
}

span {
    display: inline-block;
}

.tem {
    margin-right: 1rem;
}
</style>